<?php

namespace App\Http\Controllers\Client\Member;

use App\Models\Ass;
use App\Models\AssMember;
use App\Http\Controllers\RootController as Controller;
use Illuminate\Http\Request;

class AssListController extends Controller
{
    public function handle(Request $request)
    {
        $param['type'] = (int)$request->get('type', '');
        $param['limit'] = (int)$request->get('limit', 10);


        $query = Ass::orderBy('id', 'desc');
        $query->where('type', $param['type']);
        $memberId = $this->id();

        $assIds = AssMember::where('member_id', $memberId)->pluck('ass_id');
        $query->whereIn('id', $assIds);
//        $query->whereHas('assMembers', function ($query)use($memberId) {
//            $query->where('member_id', $memberId);
//        });

        $query->with('assMembers.member');

        $query->with([
                'obj'=>function($query){
                    $query->with('nation')->select(['id', 'title', 'nation_id', 'phone', 'source', 'home_num', 'lat', 'lng', 'status', 'address']);
                }
            ])
            ;

        $paginate = $query->paginate($param['limit'])->toArray();

        /******数据 start******/
        $result = [
            'total' => $paginate['total'],
            'current_page' => $paginate['current_page'],
            'last_page' => $paginate['last_page'],
            'data' => []
        ];
        if(empty($paginate['data'])) return $this->success($result);

        foreach($paginate['data'] as $k => $v){
            $result['data'][$k] = $v;
            $result['data'][$k]['member_ids'] = [];
            foreach ($v['ass_members'] as $ass_member){
                if($ass_member['type'] == 0) $result['data'][$k]['member_ids'][] = $ass_member['member_id'];
            }
        }

        return $this->success($result);
    }
}
